#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 时间     : 2020/12/03 22:25
# 作者     : DL (584054432@qq.com)
# 网址     : https://gitee.com/dingliangPython/
# 软件版本 : Python3.7.3
# 功能     ：

import os
import sys
import time

import qdarkstyle
import win32api
import win32con
import win32event
from PyQt5.QtWidgets import QApplication, QStyleFactory
from winerror import ERROR_ALREADY_EXISTS

from pyqt5_common import APP_CONFIG_PATH, APP_NAME, show_message, show_msg
from main_window import MainWindow
import connect_database


class Application(QApplication):
    def __init__(self, argv):
        QApplication.__init__(self, argv)

    # 设置主题
    def set_window_style(self):
        self.setStyleSheet('')
        tmp = self.sender().objectName()
        if tmp in QStyleFactory.keys():
            self.setStyle(tmp)
        elif tmp == 'Qdarkstyle':
            self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())


class APP(object):
    """docstring for APP"""

    def __init__(self):
        super(APP, self).__init__()
        self.app = Application(sys.argv)
        self.gui = MainWindow()
        self.ui = self.gui.ui
        self.init_style()
        self.gui.show()
        self.app.setQuitOnLastWindowClosed(False)
        sys.exit(self.app.exec_())

    # 主题
    def init_style(self):
        self.ui.Windows.triggered.connect(self.app.set_window_style)
        self.ui.WindowsXP.triggered.connect(self.app.set_window_style)
        self.ui.windowsvista.triggered.connect(self.app.set_window_style)
        self.ui.Fusion.triggered.connect(self.app.set_window_style)
        self.ui.Qdarkstyle.triggered.connect(self.app.set_window_style)
        self.ui.Fusion.trigger()


def get_app_name():
    config_path = os.path.join(APP_CONFIG_PATH, APP_NAME, 'config.db')
    if not os.path.exists(config_path):
        show_msg("配置文件：{}不存在，无法启动".format(config_path))
        os._exit(0)
    config = {'databasepath': config_path, 'type': 'sqlite'}
    connect = connect_database.Connect(**config)
    sql = "SELECT * FROM APPConfig"
    data = connect.loadSql(sql, 1)
    if not data:
        return int(time.time())
    return "{APPName}{APPID}".format(**data[0])


if __name__ == '__main__':
    app_name = get_app_name()
    # 程序互斥防多启
    mutexname = "{}".format(app_name)  # 互斥体命名
    mutex = win32event.CreateMutex(None, False, mutexname)
    if win32api.GetLastError() == ERROR_ALREADY_EXISTS:
        win32api.MessageBox(0, u'程序已运行，禁止重复启动！！！', u'警告', win32con.MB_OK)
        os._exit(0)
    app = APP()